<template>
	<view class="page">
		<!-- <u-navbar title="视频" :bgColor="bgColor" leftIconColor="#fff" :titleStyle="titleStyle" :placeholder="true"
			:autoBack="true"></u-navbar> -->
		<headerinfo></headerinfo>
		<view class="titlesss"><el-dropdown @command="fabu_handleCommand">
				<view class="notice" style="margin-right: 30px;">
					发视频
					<i class="el-icon-arrow-down"></i>
				</view>
				<el-dropdown-menu slot="dropdown">
					<el-dropdown-item command="0" v-if="!form.isMylife">我的草稿</el-dropdown-item>
					<el-dropdown-item command="1">发文章</el-dropdown-item>
					<el-dropdown-item command="2">发图文</el-dropdown-item>
					<el-dropdown-item command="3">发视频</el-dropdown-item>
				</el-dropdown-menu>
			</el-dropdown>
			<span>发布视频</span>
			<span class="text-danger" v-if="form.isMylife">(个人生活)</span>
		</view>
		<view class="form">
			<view class="imgList">

				<view class="list" @click="chooseVideo" v-if="form.videos.length == 0">
					<i class="iconfont">&#xe609;</i>
					<view class="">添加视频</view>
				</view>
				<view class="list" @click="chooseVideo" v-else>
					<image :src="form.videos[0]+'?x-oss-process=video/snapshot,t_7000,f_jpg,w_160,h_200,m_fast'"
						mode=""></image>
				</view>
			</view>

			<view class="icon" v-if="form.videos.length > 0" @click="toViewVide()">
				<span>预览视频</span>
			</view>
			<view class="smalldesc" v-if="(!familyMemberId)  && (!form.isMylife)">
				共享文章，如果和自身家庭无关，可以不勾选相关家庭信息
			</view>
			<u-cell-group>
				<view class="" v-if="!familyId">
					<u-cell :title="form.isMylife?'生活分类':'文章分类'" @click="fenleiDia = true" :value="fenleiName?fenleiName:'请选择'"
						:isLink="true"></u-cell>
					<u-cell title="发布到哪个家庭" v-if="!form.isMylife" @click="familyDia = true"
						:value="familyName?familyName:'请选择'" :isLink="true"></u-cell>
					<u-cell title="选择参与的家庭成员" v-if="userList.length > 0 && !form.isMylife" @click="userlistDia = true"
						:value="checkedUserName?checkedUserName:'请选择'" :isLink="true"></u-cell>
					<view class="kaiguanlist" v-if="!form.isMylife">
						<span>分享文章到所有人</span>
						<u-switch v-model="form.shareToAll" activeColor="#de4849"></u-switch>
					</view>
					<view class="kaiguanlist" v-if="!form.isMylife && systemUser">
						<span>分享文章到首页：{{ArticleCategoryName?ArticleCategoryName:''}}</span>
						<u-switch @change="changesystemArticle" v-model="form.systemArticle"
							activeColor="#de4849"></u-switch>
					</view>
					<view class="kaiguanlist" @click="selectorVisible = true"
						v-if="!form.isMylife && systemUser && form.systemArticle">
						<span>{{ArticleCategoryName?ArticleCategoryName:''}} ></span>
					</view>
				</view>

			</u-cell-group>
			<textarea placeholder="说点什么吧..." v-model="form.content" class="contentArea"></textarea>
		</view>

		<view class="" style="height: 100rpx;">

		</view>
		<view class="lastBtn">
			<!-- v-if="!form.isDraftData" -->
			<span class="bg-success" v-if="(!form.isDraftData) && (!form.isMylife)" @click="submit(1)">存草稿</span>
			<!-- :class="form.isDraftData?'isDraftDataBtn':''" class="fabu" -->
			<span :class="(form.isDraftData || form.isMylife)?'isDraftDataBtn':''" class="fabu" @click="submit()">发布</span>
		</view>
		<u-picker :show="fenleiDia" @cancel="fenleiDia = false" :columns="tabTitle" keyName="name"
			@confirm="fenleconfirm"></u-picker>

		<u-popup :show="familyDia">
			<selectpicker @closeDia="familyDia = false" @checkedUser="familyConfim" :list="familylist"
				@close="familyDia = false"></selectpicker>
		</u-popup>
		<!-- <u-picker :show="familyDia" @cancel="familyDia = false" :columns="familylist" keyName="label"
			@confirm="familyConfim"></u-picker> -->
		<u-popup :show="userlistDia">
			<selectpicker @checkedUser="checkedUser" :list="userList" @closeDia="userlistDia = false"></selectpicker>
		</u-popup>

		<w-picker :visible.sync="selectorVisible" mode="selector" default-type="name" :default-props="defaultProps"
			:options="wenzhangfenlei" @confirm="onConfirm($event,'selector')" ref="selector"></w-picker>
	</view>
</template>

<script>
	import minxins from '../../common/upload.js';
	const util = require('@/common/refresh.js');
	export default {
		mixins: [minxins],
		components: {},
		data() {
			return {
				wenzhangfenlei: [],
				selectorVisible: false,
				defaultProps: {
					label: "name",
					value: "id"
				},
				ArticleCategoryName: '',
				bgColor: '#de4849',
				titleStyle: {
					color: '#fff'
				},
				fenleiDia: false,
				familyDia: false,
				userlistDia: false,
				checkedUserName: '',
				userList: [],
				familyName: '',
				tabTitle: [],
				systemUser: false, // 系统管理员
				fenleiName: '',
				familylist: [],
				form: {
					categoryId: '',
					content: '',
					contentOri: '',
					title: '',
					familyAttenders: [],
					familyIds: [],
					htmlArticle: false,
					systemArticle: false,
					images: [],
					posterUrl: '',
					shareToAll: false,
					isDraft: false,
					location: '',
					videoCoverSeconds: '1',
					videos: [],
					videosOri: [],
					privacy: 'all',
					systemArticleCategory: ''
				},
				isMylife: '',
				isSubmit: false,
				isSubmit2: false,
				familyMemberId: '',
				familyId: '',
				isFromCaogao: false
			};
		},
		onLoad(e) {
			console.log('video', e);
			if (e && e.data) {
				this.isFromCaogao = true
				this.form = JSON.parse(decodeURIComponent(e.data));
				this.form.isDraftData = true
				this.form.articleId = this.form.docId
				this.form.familyAttenders = []
				this.form.familyIds = []
				this.form.categoryId = this.form.categoryId ? this.form.categoryId : ''
				this.form.content = this.form.contentOri = this.form.content ? this.form.content : ''
				if (this.form.videos) {
					this.form.videosOri = this.form.videos
					this.form.videos = [...this.form.videos]
				} else {
					this.form.videosOri = []
					this.form.videos = []
				}
			}

			if (e && e.isMylife) {
				this.isMylife = this.form.isMylife = e.isMylife
			}

			if (e.familyMemberId) {
				this.familyMemberId = e.familyMemberId

			}

			if (e.familyId) {
				this.familyId = e.familyId
				this.form.familyIds = [e.familyId]
				this.checkedUserName = '123'
				this.form.familyAttenders = [this.familyMemberId]

			}

			let systemUser = uni.getStorageSync('systemUser') ? uni.getStorageSync('systemUser') : false
			this.systemUser = systemUser

			if (this.form.isMylife) {
				this.getAllLifeCategories();
			} else {
				this.getAllCategories();
			}
			this.getMyfamilyData()



			this.$api.getSystemArticleCategory().then(res => {

				this.wenzhangfenlei = res
				if (res.length > 0) {
					this.ArticleCategoryName = res[0].name
					this.form.systemArticleCategory = res[0].id
				}


				console.log(res)

			})
		},
		onShow() {},
		onUnload() {},
		mounted() {},
		// 2：需要在退出页面的时候销毁这个监听事件
		destroyed() {},
		methods: {
			fabu_handleCommand(e) {
				console.log(e)
				if (e == 0) {
					uni.navigateTo({
						url: `/pages/draft/index`
					})
				} else if (e == 1) {
					let url = '/pages/create/article'
					if (this.form.isMylife) {
						url = url + '?isMylife=1'
					}
					uni.navigateTo({
						url: url
					})
				} else if (e == 2) {
					let url = '/pages/create/picture'
					if (this.form.isMylife) {
						url = url + '?isMylife=1'
					}
					uni.navigateTo({
						url: url
					})
				} else {
					let url = '/pages/create/video'
					if (this.form.isMylife) {
						url = url + '?isMylife=1'
					}
					uni.navigateTo({
						url: url
					})
				}
			},
			changesystemArticle() {
				console.log(this.form.systemArticle)

				if (!this.form.systemArticle) {
					this.form.systemArticleCategory = ''
				} else {
					this.form.systemArticleCategory = this.wenzhangfenlei[0].id
				}
			},
			onConfirm(e) {
				console.log('onConfirm', e);
				this.form.systemArticleCategory = e.value
				this.ArticleCategoryName = e.result
			},
			getAllLifeCategories() {
				let tabBars = [];
				this.$api.getAllLifeCategories().then(res => {
					console.log(res)
					if (res) {
						for (let i in res) {
							if (this.form.lifeCategoryId) {
								if (i == this.form.lifeCategoryId) {
									this.fenleiName = res[i]
								}
							}

							tabBars.push({
								name: res[i],
								id: i,
							});

						}
						this.tabTitle.push(tabBars);


					}
				})
			},
			familyConfim(e) {
				let familyIds = []
				let familynames = []
				if (e.length > 0) {
					e.forEach(item => {
						familyIds.push(item.familyId)
						familynames.push(item.name)
					})

					this.form.familyIds = familyIds
					this.familyName = familynames.toString()
					this.familyDia = false
					if (this.form.familyIds.length == 1) {
						this.getFamUser()
					} else {
						this.userList = []
						this.checkedUserName = ''
						this.form.familyAttenders = []
					}
				}
			},
			getFamUser() {
				let data = {
					familyId: this.form.familyIds[0]
				}
				this.$api.queryFamilyMember(data).then(res => {
					console.log(res)

					let list = []

					if (res.list.length > 0) {
						res.list.forEach(item => {
							list.push({
								name: item.nickname,
								val: item.id,
								phone: item.phone,
								checked: false
							})
						})
					}

					this.userList = list
				})
			},
			checkedUser(e) {
				console.log(e)
				this.userlistDia = false
				if (e.length == 0) {
					return
				}
				this.form.familyAttenders = []
				this.checkedUserName = ''
				let arr = []
				e.forEach(item => {
					this.form.familyAttenders.push(item.val)
					arr.push(item.name)
				})

				this.checkedUserName = arr.toString()

			},
			getMyfamilyData() {

				this.$api.myFamily().then(res => {
					let familylist = [];
					uni.setStorageSync('myFamilyIndexs', []);
					if (res.familyInfo) {
						for (let i in res.familyInfo) {
							familylist.push({
								familyId: i,
								family: res.familyInfo[i].family
							});
						}
						if (familylist.length > 0) {
							familylist.forEach((item, index) => {
								console.log(item);
								item.name = item.label = item.family.familyName;
								item.id = item.familyId;

							});
						}

						console.log(familylist);
						this.familylist = familylist


					}
				});
			},
			toViewVide() {
				let url = this.form.videos[0]

				uni.navigateTo({
					url: `/pages/create/viewVideo?url=${url}`
				})
			},
			getAllCategories() {
				let tabBars = [];
				this.$api.getAllCategories().then(res => {
					if (res) {
						for (let i in res) {
							if (this.form.categoryId) {
								if (i == this.form.categoryId) {
									this.fenleiName = res[i]
								}
							}

							tabBars.push({
								name: res[i],
								id: i,
							});

						}
						this.tabTitle.push(tabBars);
					}
				});
			},
			submit: util.throttle(function(type) {
				if (this.form.videos.length == 0) {
					return this.$Show.show('请上传视频')
				}
				if (this.form.isMylife == 1) {
					if (type == 1) {
						this.form.isDraft = true
					}

					//草稿进来的
					if (this.form.isDraftData) {
						this.form.isDraft = false
						this.form.lifeId = this.form.docId
					}

					if (this.form.videos.length == 0) {
						return this.$Show.show('请上传视频')
					}

					if (this.form.lifeCategoryId == '') {
						return this.$Show.show('请选择生活分类')
					}


					if (this.form.content == '') {
						return this.$Show.show('请输入描述')
					}


					if (this.familyMemberId) {
						this.form.familyMemberId = this.familyMemberId
						this.$api.upsertOtherLife(this.form).then(res => {
							if (type == 1) {
								this.$Show.show('保存成功')
							} else {
								this.$Show.show('发布成功')
							}
							uni.setStorageSync('lifeneedRefresh', 1)
							// uni.removeStorageSync('videoForm')
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/life/index'
								})
							}, 1000)
						})
					} else {
						this.$api.upsertLife(this.form).then(res => {
							if (type == 1) {
								this.$Show.show('保存成功')
							} else {
								this.$Show.show('发布成功')
							}
							uni.setStorageSync('lifeneedRefresh', 1)
							// uni.removeStorageSync('videoForm')
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/life/index'
								})
							}, 1000)
						})
					}

				} else {
					if (type == 1) {
						this.form.isDraft = true
					} else {
						if (this.form.categoryId == '') {
							return this.$Show.show('请选择文章分类')
						}
						if (!this.form.shareToAll && !this.form.systemArticle) {
							if (this.form.familyIds.length == 0) {
								return this.$Show.show('请选择家庭')
							}

							if (this.form.familyIds.length == 1 && this.checkedUserName == '') {
								return this.$Show.show('请选择家庭成员')
							}
						}
						if ((!this.form.content) || this.form.content == '') {
							return this.$Show.show('说点什么吧...')
						}
					}

					//草稿进来的
					if (this.form.isDraftData) {
						this.form.isDraft = false
						this.form.articleId = this.form.docId
					}
					console.log('throttle', this.form)
					this.$api.upsertArticle(this.form).then(res => {
						this.isSubmit = true
						uni.setStorageSync('needRefresh', 1)
						if (type == 1) {
							this.$Show.show('草稿保存成功')
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/draft/index'
								})
							}, 1000)
						} else {
							this.$Show.show('发布成功')
							setTimeout(() => {
								uni.navigateTo({
									url: '/pages/tabbar/index/index?index=1'
								})
							}, 1000)
						}
					})
				}
			}),

			fenleconfirm(e) {
				console.log(e)
				this.fenleiName = e.value[0].name

				if (this.form.isMylife == 1) {
					this.form.lifeCategoryId = e.value[0].id
				} else {
					this.form.categoryId = e.value[0].id
				}

				this.fenleiDia = false
			},
			chooseVideo() {
				uni.chooseVideo({
					count: 1,
					compressed: false,
					success: (res) => {
						console.log(res)
						let name = Date.now() + '_' + Math.round(Math.random() * 100000000)

						// // #ifdef APP-PLUS
						// let houzui = res.tempFilePath.substring(res.tempFilePath.lastIndexOf('.') + 1)
						// // #endif
						// #ifdef MP-WEIXIN
						let houzui = res.tempFilePath.substring(res.tempFilePath.lastIndexOf('.') + 1)
						// #endif

						// #ifdef H5
						let houzui = res.name.substring(res.name.lastIndexOf('.') + 1)
						// #endif
						let fileName = name + '.' + houzui
						let path = res.tempFilePath
						console.log('fileName',fileName,path)


						let maxVideoMegBytes = uni.getStorageSync('maxVideoMegBytes') ? uni.getStorageSync(
							'maxVideoMegBytes') : 100

						let resSize = res.size;
						console.log('res',res)
						let maxSize = maxVideoMegBytes * 1024 * 1024
						if (resSize > maxSize) {
							uni.showToast({
								title: `大小不能超过${maxVideoMegBytes}MB`,
								icon: 'none'
							});
							return
						}

						console.log('压缩后', res.tempFilePath)
						let familyId = uni.getStorageSync('familyId') ? uni.getStorageSync('familyId')[0] : ''

						this.uploadUserImage(res.tempFilePath, 'video', fileName, familyId, (url) => {
							console.log(url)
							this.form.videos = [url]
							console.log(this.form)
						})

						// uni.showLoading({
						// 	title: '压缩中...'
						// });
						// uni.compressVideo({
						// 	src: path,
						// 	quality: 'low', 
						// 	success: (res)=> {

						// 	},
						// 	fail: (err)=> {
						// 		console.log(err)
						// 		this.$Show.show('视频压缩失败')
						// 	}
						// })

					}
				});

			}
		}
	};
</script>

<style lang="scss" scoped>
	.smalldesc {
		padding: 20rpx;
	}

	.titlesss {
		width: 60%;
		margin: 20px auto;
		font-size: 42rpx;
	}

	.kaiguanlist {
		padding: 20rpx 30rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1px solid #e6e6e6;
	}

	.page {
		background-color: #fff;

		.lastBtn {
			position: fixed;
			width: 600px;
			bottom: 0;
			border: 1px solid #e8e8e8;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 30rpx 50rpx 30rpx;
			background-color: #fff;
			z-index: 10000;
			left: 50%;
			transform: translateX(-50%);

			span {
				display: block;
				width: 48%;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border: 1px solid #e8e8e8;
				border-radius: 10rpx;
				cursor: pointer;
			}

			.fabu {
				border-color: #de4849;
				background-color: #de4849;
				color: #fff;
			}

			.isDraftDataBtn {
				width: 100% !important;
			}

			.isDraftDataBtn2 {
				width: 50% !important;
			}

		}

		.form {
			border-top: 1px solid #f9f9f9;
			padding: 0 30rpx;
			box-sizing: border-box;
			width: 60%;
			margin: 0 auto;
			box-shadow: 0 0 3px #ccc;
			border-radius: 20rpx;
			position: relative;
			margin: 20rpx auto;

			.icon {
				text-align: center;
				padding-bottom: 40rpx;
				font-size: 24rpx;
				padding: 5px 20px;
				border-radius: 20px;
				background-color: #f1f1f1;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 200rpx;
				margin: 0 auto;
				margin-bottom: 40rpx;

			}

			textarea {
				padding: 10rpx 30rpx;
			}

			.imgList {
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 40rpx 0;

				.list {
					width: 320rpx;
					height: 400rpx;
					display: flex;
					align-items: center;
					background-color: #f8f8f8;
					justify-content: center;
					flex-direction: column;
					border-radius: 5rpx;
					margin-bottom: 20rpx;
					position: relative;

					image {
						width: 100%;
						height: 100%;
					}

					view {
						font-size: 30rpx;
						color: #b7b7b7;
						margin-top: 30rpx;
					}

					.iconfont {
						color: #b7b7b7;
						font-size: 60rpx;
					}

					.fileImg {
						width: 100%;
						height: 100%;
					}
				}

				.nobg {
					background-color: #fff;
				}

				.zhanwei {
					visibility: hidden;
					height: 0;
					margin: 0;
				}
			}

			.titleBox {
				height: 100rpx;
				font-size: 32rpx;
				border-bottom: 1px solid #f8f8f8;
			}

			.contentArea {
				font-size: 30rpx;
				width: 100%;
				height: 300rpx;
				margin-top: 30rpx;
			}
		}
	}
</style>